package cn.darkhorse.device.iot.parser;

import cn.darkhorse.device.pojo.MqttData;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.utils.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 塔石网关，数据解析器
 */
@Component("TasTekParser")
public class TasTekParser extends BaseParser {


    private static final Logger log = LoggerFactory.getLogger(TasTekParser.class);

    @Override
    Map<String, Object> doParse(MqttData data, String gatewayDeviceId) {
        String json = data.getData();
        JSONObject jsonObject = JSONObject.parse(json);

        // Step.1 获取设备点表
        Set<String> pointIds = getPointIds(gatewayDeviceId);

        // Step.2 解析
        Map<String, Object> pointValueMap = new HashMap<>();
        pointIds.forEach(pointId-> {
            Object o = jsonObject.getJSONObject("params").get(pointId);
            if (o == null) {
                return;
            }
            pointValueMap.put(pointId, o);
        });

//        addToCache(gatewayDeviceId, pointValueMap);
        return pointValueMap;
    }

    @Override
    Map<String, Object> doParse(MqttData data, String gatewayDeviceId, Set<String> pointIds) {
        String json = data.getData();
        JSONObject jsonObject = JSONObject.parse(json);
//
        log.debug("数据构建开始:" + pointIds);
        // Step.1 获取设备点表
//        Set<String> pointIds = getPointIds(gatewayDeviceId);

        // Step.2 解析
        Map<String, Object> pointValueMap = new HashMap<>();
        pointIds.forEach(pointId-> {
            Object o = jsonObject.getJSONObject("params").get(pointId);
            if (o == null) {
                return;
            }
            pointValueMap.put(pointId, o);
        });
        log.debug("数据构建结束:" + pointValueMap);
        return pointValueMap;
    }


    @Override
    public LocalDateTime getCreatedAd(MqttData data) {
        String json = data.getData();
        JSONObject jsonObject = JSONObject.parse(json);
        LocalDateTime localDateTime = null;
        try {
            Long timestamp = Long.parseLong(jsonObject.get("id").toString());
            localDateTime = DateUtils.getLocalDateTime(timestamp);
        }catch(Exception e){
            System.out.println(e);
            localDateTime = LocalDateTime.now();
        }

        return localDateTime;
    }

}
